package com.demo;

import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

import javax.annotation.Resource;

import lombok.extern.slf4j.Slf4j;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;

import com.jaws.demo.ClientDemoApplication;
import com.taobao.stresstester.StressTestUtils;
import com.taobao.stresstester.core.StressResult;
import com.taobao.stresstester.core.StressTask;

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = ClientDemoApplication.class, webEnvironment = SpringBootTest.WebEnvironment.MOCK)
@WebAppConfiguration
@Slf4j
public class RedisIncrease extends AbstractTest{
	
	@Resource
	private RedisTemplate<Object, Object> redisTemplate;

	private final String STOCK = "mj.stock";
	
	private final Long DECREASE = 2L;
	
	private AtomicInteger count = new AtomicInteger(0);
	
	private AtomicInteger addCount = new AtomicInteger(0);;
	
	private AtomicInteger minusCount = new AtomicInteger(0);;
	
	@Test
	public void test(){
		redisTemplate.setValueSerializer(new StringRedisSerializer());
		redisTemplate.opsForValue().set(STOCK, "0");
		StressResult stressResult = StressTestUtils.test(50, 200, new StressTask() {

            public Object doTask() throws Exception {
            	
            	count.incrementAndGet();
            	
            	if(new Random().nextBoolean()){
            		addCount.incrementAndGet();
                	Long afterStock = redisTemplate.opsForValue().increment(STOCK, 1);
                	log.info(Thread.currentThread().getName() + ",add success:"+ afterStock);

            	}else{
            		minusCount.incrementAndGet();
                	Long afterStock2 = redisTemplate.opsForValue().increment(STOCK, -1);
                	log.info(Thread.currentThread().getName() + ",minus success:"+ afterStock2);
            	}
                return null;
            }
        },10);
		//数据格式化  
		log.info("total:"+count);
		log.info("add:"+addCount);
		log.info("minus:"+minusCount);
	    System.exit(0);

	}

}
